﻿using ScannerApp.Common;
using ScannerApp.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Forms;
using System.Drawing;
using ScannerApp.Model;
using AutoUpdate.Log;
using System.Threading;
using static ScannerApp.Common.PopMessageHelper;

namespace ScannerApp
{
    /// <summary>
    /// VitalityAnalysis.xaml 的交互逻辑
    /// </summary>
    public partial class Dilution : Window
    {
        ScanApp.ScanAppSoapClient sa = new ScanApp.ScanAppSoapClient();
        public Dilution()
        {
            InitializeComponent();
            czy.Text = publicclass.UserName;
        }

        private void close_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

            MessageBoxResult result = System.Windows.MessageBox.Show("系统是否关闭？", "提示", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                System.Windows.Application.Current.Shutdown();    Environment.Exit(0);
            }
            else
            {

            }

        }

        private void tm1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {

            if (e.Key == Key.Enter)
            {
                this._loading.Visibility = Visibility.Visible;

                //button1.Focus();
                LoadData(tm1.Text);
                tm1.Text = "";
                this._loading.Visibility = Visibility.Collapsed;
            }



        }
        private void read_Click(object sender, RoutedEventArgs e)
        {
            this._loading.Visibility = Visibility.Visible;

            LoadData(tm1.Text);
            this._loading.Visibility = Visibility.Collapsed;

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.WindowState = System.Windows.WindowState.Maximized;
            tm1.Focus();
            sysname.Text = publicclass.SystemName;
            string preurl = Common.ConfigHelper.GetEndpointClientAddress("ScanAppSoap");

            Uri uri = new Uri(preurl);
            string imageurl = uri.Scheme + "://" + uri.Host + "/" + publicclass.SystemLogo;
            // Console.WriteLine(uri.Host);
            this.tb_1.Source = new BitmapImage(new Uri(imageurl));
            tm();
            ReflashGridData();


        }
        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                DragMove();
            }
        }

        void LoadData(string tm)
        {
            if (tm.Length != 15)
            {
                Tips(tm + "条码无效");
            }
            if (tm.Length <= 1)
            {
                Tips(tm + "条码无效");
            }
            if (tm == "00000000")//打印保存
            {

                string msg = sa.Update_boar_collection_collection("collection_save", "", zydh.Text.Trim());
                if (zydh.Text.Trim() != "" && msg == "")
                {
                    printBarCode();
                    string para = "{\"EventType\":\"种禽稀释\",\"EventID\":\"" + publicclass.MacAddress + "\",\"EventTitle\":\"" + zydh.Text + "\",\"Log_Content\":\"" + "【采集保存(状态)】 → 15\",\"UserID\":\"" + publicclass.Id + "\",\"UserName\":\"" + publicclass.UserName + "\"}";
                    string msglog = sa.Sys_log(para);
                }
                else
                {
                    Tips(tm + msg);
                }
                // Clear();
            }
            else if (tm == "00000001")//提交
            {
                string msg = sa.Update_boar_collection_collection("collection_submit", publicclass.UserName, zydh.Text.Trim());
                if (zydh.Text.Trim() != "" && msg == "")
                {
                    string para = "{\"EventType\":\"种禽稀释\",\"EventID\":\"" + publicclass.MacAddress + "\",\"EventTitle\":\"" + zydh.Text + "\",\"Log_Content\":\"" + "【采集保存(提交)】 → 20\",\"UserID\":\"" + publicclass.Id + "\",\"UserName\":\"" + publicclass.UserName + "\"}";
                    string msglog = sa.Sys_log(para);
                    Clear("all");
                    ReflashGridData();
                }
                else
                {
                    Tips(tm + msg);
                }
                //Clear();
            }
            else
            {

                DataTable lsdt = sa.GetDataTable_boar_collection_collection(tm);
                if (lsdt == null)
                {
                    Clear("dd");
                    Tips(tm + "无对应订单信息");
                }
                else
                {
                    if (lsdt.Rows.Count <= 0)
                    {
                        Clear("dd");
                        Tips(tm + "无对应订单信息");
                    }
                    else
                    {
                        foreach (DataRow dr in lsdt.Rows)
                        {
                            zydh.Text = dr["id"].ToString();
                            ddbh.Text = dr["Serialnumber"].ToString();
                            cpsl.Text = dr["quantity"].ToString();
                            mfrl.Text = dr["capacity"].ToString();
                            ddjq.Text = dr["Order_date"].ToString();
                            //yysj.Text = dr["collectDate"].ToString();
                            ddzt.Text = dr["StatusName"].ToString();
                            dr["StatusName"].ToString();

                        }
                        printBarCode();
                    }
                }
            }

        }

        void Clear(string type)
        {
            if (type == "dd" || type == "all")
            {
                //bsm.Text = "";


                zydh.Text = "";
                ddbh.Text = "";
                cpsl.Text = "";
                mfrl.Text = "";
                ddjq.Text = "";
                //yysj.Text = "";
                ddzt.Text = "";
            }

        }

        void tm()
        {
            System.Drawing.Image image = BarcodeHelper.GenerateCZ("00000000", 200, 50);

            DisplayImg(image, cztm);


            System.Drawing.Image image2 = BarcodeHelper.GenerateCZ("00000001", 200, 50);
            DisplayImg(image2, cztm2);


        }

        void DisplayImg(System.Drawing.Image image, System.Windows.Controls.Image cimage)
        {
            //System.Drawing.Image image = BarcodeHelper.GenerateCZ("00000000", 200, 50);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);// 格式自处理,这里用 bitmap
                                                                   // 下行,初始一个 ImageSource 作为 myImage 的Source
            System.Windows.Media.Imaging.BitmapImage bi = new System.Windows.Media.Imaging.BitmapImage();
            bi.BeginInit();
            bi.StreamSource = new MemoryStream(ms.ToArray()); // 不要直接使用 ms
            bi.EndInit();
            cimage.Source = bi; // done!
            ms.Close();
        }


        void printBarCode()
        {
            try
            {
                //实例化打印对象
                PrintDocument document = new PrintDocument();

                //设置打印用的纸张,可以自定义纸张的大小(单位:mm).   当打印高度不确定时也可以不设置
                document.DefaultPageSettings.PaperSize = new PaperSize("Custum", 200, 80);

                //注册PrintPage事件，打印每一页时会触发该事件
                document.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);

                //开始打印
                //document.Print();

                //打印预览
                PrintPreviewDialog ppd = new PrintPreviewDialog();
                ppd.Document = document;
                ppd.ShowDialog();


                try
                {
                    //if (this.CurrentPrintQRCode != null && this.CurrentPrintQRCode.Count() > 0)
                    //{
                    int printtimes = 2;
                    //    for (int i = 1; i <= printtimes; i++)
                    //    {
                    //        document.Print();
                    //        Thread.Sleep(1000);
                    //    }
                    // }
                }
                catch (Exception exception)
                {
                    PopMessageHelper.ShowMessage("错误:" + exception.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

                    document.PrintController.OnEndPrint(document, new PrintEventArgs());
                }
            }
            catch (Exception e)
            {
                PopMessageHelper.ShowMessage("错误:" + e.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);
                Logger.Instance.WriteLog(publicclass.UserName + "[种源采集]" + e.Message, LogType.Error, "collection");

            }
        }
        private void pd_PrintPage(object sender, PrintPageEventArgs e) //触发打印事件
        {
            PrintWorkDocumentEntity pe = new PrintWorkDocumentEntity();
            pe.WorkID = zydh.Text;
            string PrintStr = zydh.Text;
            pe.SaleID = "测试";
            StringBuilder sb = new StringBuilder();
            sb.Append("\r\n\r\n\r\n");
            //sb.Append("*******兴隆超市*******\r\n");
            //sb.Append("品名-----数量-----价格\r\n");
            //sb.Append("精品白沙  1    8元\r\n");
            //sb.Append("张新发槟榔 1   10元\r\n");
            sb.Append("其他:   " + pe.SaleID + "\r\n");
            //sb.Append("---收银员:张三---\r\n");
            //sb.Append("---技术支持:李四---\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n");

            int ImgWidth = 200;
            int ImgHeight = 60;
            e.Graphics.DrawString(PrintStr, new Font(new System.Drawing.FontFamily("黑体"), 10), System.Drawing.Brushes.Black, 1, 1);
            BarcodeHelper.DrawPrint(e, sb.ToString(), pe.WorkID, ImgWidth, ImgHeight);
            // BarcodeHelper.GetPrintWorkIDPicture(bmp2, pe, e);
        }

        //右边处理列表
        void ReflashGridData()
        {
            DataTable lsdt = sa.GetList_boar_collection("", "collection");
            // var r = SQLLogic.GetList_boar_collection("");
            //if (r.Item1)
            datagrid1.ItemsSource = lsdt.DefaultView;
            //设置网格线

            datagrid1.GridLinesVisibility = DataGridGridLinesVisibility.All;
        }

        void Tips(string msg)
        {
            PopMessageHelper.ShowMessage("错误:" + msg + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);
            Logger.Instance.WriteLog(publicclass.UserName + "[种源采集]" + msg, LogType.Error, "collection");
            tm1.Focus(); return;
        }


    }

}
